﻿using RockBus.Configuration.Interfaces;
using RockBus.Logging.Interfaces;
using RockBus.MessageLogging.Interfaces;
using RockBus.Messages.Interfaces;
using RockBus.ServiceModel;
using System;
using System.Reflection;
using System.ServiceModel.Channels;

namespace RockBus.MessageLogging
{
    public class MessageLogger : IMessageLogger
    {
        public MessageLogger(ILogger logger, IReadOnlyConfiguration configuration)
        {
            this.Logger = logger;
            this.Configuration = configuration;
        }

        private ILogger Logger { get; set; }

        private IReadOnlyConfiguration Configuration { get; set; }

        /// <summary>
        /// Logs the content of the current message of the messageContext (depends on MessageDirection).
        /// </summary>
        /// <param name="messageContext"></param>
        public void LogMessage(IMessageContext messageContext)
        {
            if (messageContext != null)
            {
                this.LogMessage(messageContext.ToString(), messageContext.Message);
            }
        }

        /// <summary>
        /// Logs the content of the Message.
        /// </summary>
        /// <param name="message"></param>
        public void LogMessage(string logTag, IMessage message)
        {
            this.LogMessage(logTag, (message == null) ? null : message.MessageBuffer);
        }

        /// <summary>
        /// Logs the content of the Message by creating a BufferedCopy of it.
        /// </summary>
        /// <param name="message"></param>
        public void LogMessage(string logTag, ref Message message)
        {
            if (this.Configuration.InternalConfiguration.DebugMessageLoggingEnabled)
            {
                var messageBuffer = message.CreateBufferedCopy(this.Configuration.InternalConfiguration.DefaultMaxMessageBufferSize);
                this.LogMessage(logTag, messageBuffer);
                message = messageBuffer.CreateMessage();
            }
        }

        /// <summary>
        /// Logs the content of the MessageBuffer.
        /// </summary>
        /// <param name="messageBuffer"></param>
        public void LogMessage(string logTag, MessageBuffer messageBuffer)
        {
            if (this.Configuration.InternalConfiguration.DebugMessageLoggingEnabled)
            {
                Message message = (messageBuffer == null) ? null : messageBuffer.CreateMessage();
                this.Logger.LogDebug(
                    MethodBase.GetCurrentMethod(),
                    string.Format("{0}: {1}",
                        logTag,
                        (message == null) ? "null" : message.MessageAsString()));
            }
        }
    }
}
